package jd.se.borrowrequest;

import jd.se.common.Utils;
import jd.se.returnrequest.ReturnRequestDao;
import jd.se.returnrequest.ReturnRequestDto;
import org.apache.ibatis.session.SqlSession;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BorrowRequestService {
    public Map<String, Object> getBorrowRequest(String to_id) {
        SqlSession sess = Utils.openSession();
        BorrowRequestDao borrowRequestDao = sess.getMapper(BorrowRequestDao.class);
        List<BorrowRequestShow> borrowRequestList = borrowRequestDao.showBorrowRequest(to_id);
        List<ReturnRequestDto> borrowRequestDtos = new ArrayList<>();
        SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //设置格式
        for(BorrowRequestShow bitem : borrowRequestList){             //获得带格式的字符串
            borrowRequestDtos.add(new ReturnRequestDto(bitem.getBorrower_id(),bitem.getB_id(),bitem.getU_name(),bitem.getB_name(),format.format(bitem.getTime())));
        }
        Map<String, Object> requests = new HashMap<>();
        requests.put("list", borrowRequestDtos);
        return requests;
    }

    public void confirmBorrowRequest(BInfo bInfo){
        SqlSession sess = Utils.openSession();
        BorrowRequestDao borrowRequestDao = sess.getMapper(BorrowRequestDao.class);
        borrowRequestDao.updateBookStatus(bInfo);
        borrowRequestDao.insertBorrow(bInfo);
        borrowRequestDao.deleteBorrowRequest(bInfo);
        sess.commit();
    }

    public void refuseBorrowRequest(BInfo bInfo){
        SqlSession sess = Utils.openSession();
        BorrowRequestDao borrowRequestDao = sess.getMapper(BorrowRequestDao.class);
        borrowRequestDao.deleteBorrowRequest(bInfo);
        sess.commit();
    }
}
